from flask import Blueprint, request, jsonify
from models import db, ResumeTemplate

template_bp = Blueprint('template', __name__)

@template_bp.route('/api/templates', methods=['GET'])
def get_templates():
    templates = ResumeTemplate.query.all()
    return jsonify([template.to_dict() for template in templates])

@template_bp.route('/api/templates', methods=['POST'])
def create_template():
    data = request.get_json()
    template = ResumeTemplate(**data)
    db.session.add(template)
    db.session.commit()
    return jsonify({'message': '创建成功', 'id': template.id}), 201

@template_bp.route('/api/templates/<int:id>', methods=['PUT'])
def update_template(id):
    template = ResumeTemplate.query.get_or_404(id)
    data = request.get_json()
    for key, value in data.items():
        setattr(template, key, value)
    db.session.commit()
    return jsonify({'message': '修改成功'})

@template_bp.route('/api/templates/<int:id>', methods=['DELETE'])
def delete_template(id):
    template = ResumeTemplate.query.get_or_404(id)
    db.session.delete(template)
    db.session.commit()
    return jsonify({'message': '删除成功'})

@template_bp.route('/api/templates/<int:id>/set-default', methods=['PUT'])
def set_default_template(id):
    templates = ResumeTemplate.query.all()
    for t in templates:
        t.is_default = False
    template = ResumeTemplate.query.get_or_404(id)
    template.is_default = True
    db.session.commit()
    return jsonify({'message': '设置默认模板成功'}) 